import 'package:hive/hive.dart';

part 'play_history.g.dart';

/// 播放历史数据模型类
/// 记录用户的音乐播放历史信息
@HiveType(typeId: 3)
class PlayHistory {
  /// 播放历史唯一标识符
  @HiveField(0)
  final String id;

  /// 音乐ID
  @HiveField(1)
  final String musicId;

  /// 播放时间
  @HiveField(2)
  DateTime? playedAt;

  /// 播放时长（毫秒）
  @HiveField(3)
  int playDuration = 0;

  /// 是否播放完成
  @HiveField(4)
  bool completed = false;

  /// 播放进度（0.0-1.0）
  @HiveField(5)
  double progress = 0.0;

  /// 播放来源（如：播放列表、搜索、收藏等）
  @HiveField(6)
  String? source;

  /// 构造函数
  PlayHistory({
    required this.id,
    required this.musicId,
    this.playedAt,
    this.playDuration = 0,
    this.completed = false,
    this.progress = 0.0,
    this.source,
  }) {
    playedAt ??= DateTime.now();
  }

  /// 从JSON创建PlayHistory对象
  factory PlayHistory.fromJson(Map<String, dynamic> json) {
    return PlayHistory(
      id: json['id'] as String,
      musicId: json['music_id'] as String,
      playedAt: DateTime.fromMillisecondsSinceEpoch(json['played_at'] as int),
      playDuration: json['play_duration'] as int,
      completed: json['completed'] is int 
          ? (json['completed'] as int) == 1 
          : json['completed'] as bool, // 处理int和bool两种格式
      progress: (json['progress'] as num).toDouble(),
      source: json['source'] as String?,
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'music_id': musicId,
      'played_at': playedAt?.millisecondsSinceEpoch,
      'play_duration': playDuration,
      'completed': completed ? 1 : 0, // 将bool转换为int
      'progress': progress,
      'source': source,
    };
  }

  /// 复制并修改部分属性
  PlayHistory copyWith({
    String? id,
    String? musicId,
    DateTime? playedAt,
    int? playDuration,
    bool? completed,
    double? progress,
    String? source,
  }) {
    return PlayHistory(
      id: id ?? this.id,
      musicId: musicId ?? this.musicId,
      playedAt: playedAt ?? this.playedAt,
      playDuration: playDuration ?? this.playDuration,
      completed: completed ?? this.completed,
      progress: progress ?? this.progress,
      source: source ?? this.source,
    );
  }

  /// 格式化播放时长为可读字符串
  String get formattedPlayDuration {
    final minutes = playDuration ~/ 60000;
    final seconds = (playDuration % 60000) ~/ 1000;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  /// 格式化播放时间为可读字符串
  String get formattedPlayedAt {
    final now = DateTime.now();
    final difference = now.difference(playedAt ?? DateTime.now());

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is PlayHistory && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'PlayHistory(id: $id, musicId: $musicId, playedAt: $playedAt, completed: $completed)';
  }
}

/// 播放统计数据模型类
/// 用于统计用户的播放习惯和数据
@HiveType(typeId: 4)
class PlayStatistics {
  /// 统计ID
  @HiveField(0)
  final String id;

  /// 总播放时长（毫秒）
  @HiveField(1)
  final int totalPlayTime;

  /// 总播放次数
  @HiveField(2)
  final int totalPlayCount;

  /// 今日播放时长（毫秒）
  @HiveField(3)
  final int todayPlayTime;

  /// 今日播放次数
  @HiveField(4)
  final int todayPlayCount;

  /// 最常播放的音乐ID列表（按播放次数排序）
  @HiveField(5)
  final List<String> mostPlayedMusicIds;

  /// 最近播放的音乐ID列表
  @HiveField(6)
  final List<String> recentlyPlayedMusicIds;

  /// 统计更新时间
  @HiveField(7)
  final DateTime updatedAt;

  /// 构造函数
  PlayStatistics({
    required this.id,
    required this.totalPlayTime,
    required this.totalPlayCount,
    required this.todayPlayTime,
    required this.todayPlayCount,
    required this.mostPlayedMusicIds,
    required this.recentlyPlayedMusicIds,
    required this.updatedAt,
  });

  /// 从JSON创建PlayStatistics对象
  factory PlayStatistics.fromJson(Map<String, dynamic> json) {
    return PlayStatistics(
      id: json['id'] as String,
      totalPlayTime: json['total_play_time'] as int,
      totalPlayCount: json['total_play_count'] as int,
      todayPlayTime: json['today_play_time'] as int,
      todayPlayCount: json['today_play_count'] as int,
      mostPlayedMusicIds: json['most_played_music_ids'] != null
          ? List<String>.from(json['most_played_music_ids'] as List)
          : <String>[],
      recentlyPlayedMusicIds: json['recently_played_music_ids'] != null
          ? List<String>.from(json['recently_played_music_ids'] as List)
          : <String>[],
      updatedAt: DateTime.fromMillisecondsSinceEpoch(json['updated_at'] as int),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'total_play_time': totalPlayTime,
      'total_play_count': totalPlayCount,
      'today_play_time': todayPlayTime,
      'today_play_count': todayPlayCount,
      'most_played_music_ids': mostPlayedMusicIds,
      'recently_played_music_ids': recentlyPlayedMusicIds,
      'updated_at': updatedAt.millisecondsSinceEpoch,
    };
  }

  /// 复制并修改部分属性
  PlayStatistics copyWith({
    String? id,
    int? totalPlayTime,
    int? totalPlayCount,
    int? todayPlayTime,
    int? todayPlayCount,
    List<String>? mostPlayedMusicIds,
    List<String>? recentlyPlayedMusicIds,
    DateTime? updatedAt,
  }) {
    return PlayStatistics(
      id: id ?? this.id,
      totalPlayTime: totalPlayTime ?? this.totalPlayTime,
      totalPlayCount: totalPlayCount ?? this.totalPlayCount,
      todayPlayTime: todayPlayTime ?? this.todayPlayTime,
      todayPlayCount: todayPlayCount ?? this.todayPlayCount,
      mostPlayedMusicIds:
          mostPlayedMusicIds ?? List<String>.from(this.mostPlayedMusicIds),
      recentlyPlayedMusicIds: recentlyPlayedMusicIds ??
          List<String>.from(this.recentlyPlayedMusicIds),
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }

  /// 格式化总播放时长为可读字符串
  String get formattedTotalPlayTime {
    final hours = totalPlayTime ~/ 3600000;
    final minutes = (totalPlayTime % 3600000) ~/ 60000;
    return '$hours小时$minutes分钟';
  }

  /// 格式化今日播放时长为可读字符串
  String get formattedTodayPlayTime {
    final hours = todayPlayTime ~/ 3600000;
    final minutes = (todayPlayTime % 3600000) ~/ 60000;
    if (hours > 0) {
      return '$hours小时$minutes分钟';
    } else {
      return '$minutes分钟';
    }
  }

  /// 计算平均每首歌播放时长
  String get averagePlayTime {
    if (totalPlayCount == 0) return '0分钟';
    final average = totalPlayTime ~/ totalPlayCount;
    final minutes = average ~/ 60000;
    final seconds = (average % 60000) ~/ 1000;
    return '$minutes分$seconds秒';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is PlayStatistics && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'PlayStatistics(id: $id, totalPlayTime: $totalPlayTime, totalPlayCount: $totalPlayCount)';
  }
}
